package com.alibaba.user.Interceptor;

import com.alibaba.basic.util.JwtUtils;
import com.alibaba.basic.util.Payload;
import com.alibaba.basic.util.RsaUtils;
import com.alibaba.system.annotation.PreAuthorize;
import com.alibaba.system.mapper.PermissionMapper;
import com.alibaba.user.domain.LoginData;
import com.alibaba.user.domain.Logininfo;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.List;


@Component
public class LoginInterceptor implements HandlerInterceptor {
    // 由于是default 所以要实现那个就实现那个 这里我们只实现prehandler
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 请求获取请求头
        String token = request.getHeader("token");
        // token不等于null，就存在
        if (token != null) {
            //获取公钥
            Logininfo logininfo = null;
            try {
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                //解密之后获取载荷数据
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                logininfo = payload.getLoginData().getLogininfo();
            } catch (ExpiredJwtException e) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"msg\":\"timeout\"}");
                return false;
            }

                if (logininfo.getType() == 1) {
                    // 1是前台用户直接放行
                    return true;
                }
                // 1.访问接口的方法
                HandlerMethod method = (HandlerMethod) handler;
                // 获取接口中的sn
                PreAuthorize preAuthorize = method.getMethodAnnotation(PreAuthorize.class);
                // 如果sn为空，则不需要权限直接放行
                if (preAuthorize == null) {

                    return true;
                } else {
                    // 获取sn权限
                    String sn = preAuthorize.sn();
                    List<String> permissions = permissionMapper.getPermissionsByLogininfoId(logininfo.getId());
                    if (permissions.contains(sn)) {
                        return true;
                    } else {
                        response.setContentType("application/json;charset=UTF-8");

                        response.getWriter().println("{\"success\":false,\"msg\":\"noPermission\"}");
                        return false;
                    }

                }
            }

        //告诉浏览器我要给你返回一个json格式的数据，浏览器就会以json格式的数据进行转换
        response.setContentType("application/json;charset=UTF-8");

        response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
        return false;
    }
}
